------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib
local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_item_buyer"] or {}
    end)
end

-------------------------------------------------------------------------------------------------------------------------------------------------
local function Wait_for_player_close_in(theNPC)
    if theNPC:IsNearPlayer(5,true) then
        return true
    else
        return false
    end
end

local function Special_item_reward_and_chat_reset(theNPC,item)
    local fn_table = {
        ["birdcage"] = function(theNPC,item)
                local function GetBird(inst)
                    return (inst.components.occupiable and inst.components.occupiable:GetOccupant()) or nil
                end
            local bird = GetBird(item)
            if bird and bird:HasTag("bird") then
                item.npc_everything_data:Add("reward_num",math.random(3,10))
                return theNPC.CHAT_TABLE["birdcage_reset_chat"]
            end
        end,
    }
    if fn_table[item.prefab] then
        return fn_table[item.prefab](theNPC,item)
    end
    return nil
end
local function Say_to_player(theNPC)
    -- local player = TheSim:FindFirstEntityWithTag("player")
    local player = theNPC:GetNearestPlayer(true)
    if player then
        theNPC.npc_base_lib:FaceToInst(player)
        local item = theNPC.buy_tar_item
        local item_type = item.npc_everything_data:Get("type")
        local chat_strs = Special_item_reward_and_chat_reset(theNPC,item) or theNPC.CHAT_TABLE[item_type]
        if chat_strs then
            theNPC.npc_base_lib:Say(chat_strs,type(chat_strs)=="table")
        end
    end    
end

local function Give_rewards(theNPC)
    -- local player = TheSim:FindFirstEntityWithTag("player")
    local player = theNPC:GetNearestPlayer(true)
    if player then
        theNPC.npc_base_lib:FaceToInst(player)
        local item = theNPC.buy_tar_item
        local reward_name = item.npc_everything_data:Get("reward_name") or "goldnugget"
        local num = item.npc_everything_data:Get("reward_num") or 5

        local DLC_CHARACTORS = {
            ["wanda_npc"] = true,
            ["wormwood_npc"] = true,
            ["wortox_npc"] = true,
            ["wurt_npc"] = true,
            -- ["wagstaff_2_npc"] = true,
        }

        if item.GetSkinBuild and item:GetSkinBuild() ~= nil then
            num = num + math.random(5)
        end
        
        if DLC_CHARACTORS[theNPC.prefab] == true then
            num = math.ceil(num*1.5)
        end

        if theNPC.prefab == "wagstaff_2_npc" then
            num = num * 3
        end

        

        if TUNING.NPC_CONFIG.REWARDS_LESS ~= true then
            num = math.ceil(num*1.5)
        end

        player.npc_base_lib:GiveItemByName(reward_name,num)
    end
end

local function Npc_leave(theNPC)
    local item = theNPC.buy_tar_item
    SpawnPrefab("npc_fx_spawn"):PushEvent("Set",{
        pt = Vector3( item.Transform:GetWorldPosition() )
    })
    SpawnPrefab("npc_fx_spawn"):PushEvent("Set",{
        pt = Vector3( theNPC.Transform:GetWorldPosition() )
    })
    item:Remove()
end
-------------------------------------------------------------------------------------------------------------------------------------------------
local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    -- Time_Out_Leave(inst)
    
    -- theNPC.npc_base_lib:Equip_Random_Hat()
    -- theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()
    theNPC:AddTag("INLIMBO")
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
    -- theNPC:AddTag("Unable_To_Refuse")
    SpawnPrefab("npc_fx_spawn"):PushEvent("Set",{
        pt = Vector3(theNPC.Transform:GetWorldPosition())
    })

    theNPC.npc_event = inst.prefab
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end

    if theNPC.buy_tar_item == nil then
        theNPC:Remove()
        return
    end


    if theNPC.event_step == nil then
        if TUNING.NPC_CONFIG.CUSTOMER_VISIT_ALERT ~= false then
            if not theNPC.buy_tar_item:HasTag("no_announce") then
                theNPC.npc_base_lib:Announce(theNPC.CHAT_TABLE.announce,true)
            end
        end
        theNPC.buy_tar_item:AddTag("INLIMBO")
        theNPC.buy_tar_item:AddTag("notarget")
        theNPC.buy_tar_item:AddTag("noattack")
        theNPC.buy_tar_item:AddTag("invisible")
        theNPC.event_step = 1    
    elseif theNPC.event_step == 1 then
        if Wait_for_player_close_in(theNPC) == true then
            theNPC.event_step = theNPC.event_step + 1
        end
    elseif theNPC.event_step == 2 then
        Say_to_player(theNPC)
        theNPC.event_step = theNPC.event_step + 1        
    elseif theNPC.event_step == 3 then
        if theNPC.npc_everything_data:Add("wait_time 00",0.5) >= 2 then
            theNPC.event_step = theNPC.event_step + 1
        end
    elseif theNPC.event_step == 4 then
        theNPC.npc_base_lib:Action_Give()
        Give_rewards(theNPC)     
        theNPC.event_step = theNPC.event_step + 1
    elseif theNPC.event_step == 5 then
        if theNPC.npc_everything_data:Add("wait_time 01",0.5) >= 2 then
            theNPC.event_step = theNPC.event_step + 1
        end   
        if theNPC.npc_everything_data:Add("wait_time 01",0) >= 1 then
            theNPC.npc_base_lib:FaceToInst(theNPC.buy_tar_item)
        end
    elseif theNPC.event_step == 6 then
        Npc_leave(theNPC)
    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_item_buyer", fn)
